'use strict';

const {
	create
} = require("domain");

const db = uniCloud.database()
const dbCmd = db.command;
exports.main = async (event, context) => {
	const {
		userId,
		articleId,
		content,
		comment_id = '',
		reply_id = '',
		is_reply = false
	} = event;
	//获取用户，文章信息，找到指定文章，追加评论
	let user = await db.collection('user').doc(userId).get();

	user = user.data[0];
	let article = await db.collection('article').doc(articleId).get();
	const comments = article.data[0].comments;


	const generateId = (number) => {
		return Number(Math.random().toString().substr(3, number) + Date.now()).toString(36);
	};
	let commentObj = {
		comment_id: generateId(5),
		comment_content: content,
		create_time: Date.now(),
		is_reply: is_reply,
		replyArr: [],
		author: {
			author_id: user._id,
			author_name: user.author_name,
			avatar: user.avatar,
			professional: user.professional
		}
	};
	if (comment_id === '') {
		commentObj.replyArr = [];
		commentObj = dbCmd.unshift(commentObj)
	} else {
		//获取当前评论的集合，在这个集合里面找到指定的评论，修改repleArr属性
		let commentAuthor = null;
		let commentIndex = comments.findIndex(item => item.comment_id === comment_id);
		// 如果找不到评论，返回错误
		if (commentIndex === -1) {
			return {
				code: -1,
				data: {
					msg: '找不到目标评论'
				}
			}
		}

		if (is_reply) {
			commentAuthor = comments[commentIndex].replyArr.find(item => item.comment_id === reply_id).author
				.author_name;
		} else {
			commentAuthor = comments.find(item => item.comment_id === comment_id).author.author_name;
		}

		commentObj.to = commentAuthor;
		commentObj = {
			[commentIndex]: {
				replyArr: dbCmd.unshift(commentObj)
			}
		}
	}

	await db.collection('article').doc(articleId).update({
		comments: commentObj
	})

	return {
		code: 0,
		data: {
			msg: '提交成功'
		}
	}

};